using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace SolarWinds.Widgets
{
    public class Oscilloscope : Widget
    {
        public double[] Samples;
        private Texture2D mTexture;
        private readonly Rectangle mSrcRect = new Rectangle(16, 32, 16, 16);

        public Oscilloscope(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
        }

        protected internal override void PaintEvent()
        {
            base.PaintEvent();

            DrawOscilliscope();
        }

        private void DrawOscilliscope()
        {
            if (Samples == null)
            {
                return;
            }

            int sampleCount = Samples.Length;
            double max = 0;

            for (int i = 0; i < sampleCount; ++i)
            {
                double abs = Math.Abs(Samples[i]);
                if (abs > max)
                {
                    max = abs;
                }
            }
            max *= 2;

            for (int i = 0; i < sampleCount; ++i)
            {
                int x = i;
                var y = (int)(((Samples[i] / max) + 0.5f)  * Height);

                var destRect = new Rectangle(ScreenPosition.X + x, ScreenPosition.Y + y, 1, 1);

                SpriteBatch.Draw(mTexture, destRect, mSrcRect, Color.White);
            }
        }

        protected override void LoadContent()
        {
            base.LoadContent();

            mTexture = Game.Content.Load<Texture2D>(@"Textures\tiles");
        }

        protected override void UnloadContent()
        {
            base.UnloadContent();

            if (mTexture != null)
            {
                mTexture.Dispose();
                mTexture = null;
            }
        }
    }
}